#!/usr/bin/env python
#coding=utf-8

import json
from hashlib import md5

from flask import Blueprint, request, session, redirect, current_app, abort, url_for

from aladin.helpers import render_template, log_debug, show_admin_success
from aladin.database import db

from app.models.user import User, UserAdmin

index = Blueprint('index', __name__)

@index.route('/')
def welcome():
    
    admin_name = session.get('admin_name')
    if not admin_name:
        return redirect('/signin')

    return redirect('/user/')


@index.route('/signin', methods=['GET', 'POST'])
def signin():
    if request.method == 'GET':
        return render_template('account/signin.html', f={}, errormsg={})

    form = request.form
    mobile = form.get('mobile')
    password = form.get('password')
    errormsg = {}

    log_debug(form)

    if not mobile:
        errormsg['mobile'] = u'必填项'

    if not password:
        errormsg['password'] = u'必填项'

    if errormsg:
        return render_template('account/signin.html', f=form, errormsg=errormsg)

    u = User.query.filter(User.mobile == mobile).first()
    if u is None:
        errormsg['mobile'] = u'用户不存在'
        return render_template('account/signin.html', f=form, errormsg=errormsg)

    md5_pwd = md5(password).hexdigest()
    md5_pwd = md5(md5_pwd+u.salt).hexdigest()
    if u.password != md5_pwd:
        errormsg['password'] = u'密码错误'
        return render_template('account/signin.html', f=form, errormsg=errormsg)

    ua = UserAdmin.query.filter(UserAdmin.uid == u.uid).first()
    if ua is None:
        errormsg['mobile'] = u'没有权限登录'
        return render_template('account/signin.html', f=form, errormsg=errormsg)

    session['admin_id']   = u.uid
    session['admin_name'] = u.mobile
    session['uid']        = u.uid
    session['mobile']     = u.mobile
    session['avatar']     = u.avatar
    return redirect('/user/')
    
@index.route('/signout')
def signout():
    """
    登出系统
    """
    session.clear()
    return show_admin_success(u'退出登录', u'退出登录成功', url_for('index.signin'))
        


